﻿@namespace iPanel.Components
@using System.Collections.Immutable
@using iPanel.Model
@using Microsoft.FluentUI.AspNetCore.Components.DesignTokens
@inherits FluentComponentBase

@{
    var additionalButtonAttributes = new Dictionary<string, object>(AdditionalAttributes ?? ImmutableDictionary<string, object>.Empty)
    {
        { "aria-haspopup", "true" },
        { "aria-expanded", _visible },
        { "onkeydown", (KeyboardEventArgs args) => OnKeyDown(args) }
    };
}

<FluentButton Id="@MenuButtonId" Title="@Title" Appearance="@ButtonAppearance" IconStart="@IconStart" @onclick="ToggleMenu" Disabled="@(!Items.Where(i => !i.IsDivider).Any())" AdditionalAttributes="@additionalButtonAttributes" Class="@ButtonClass">
    @if (string.IsNullOrWhiteSpace(Text))
    {
        <FluentIcon Value="@_icon" Color="@IconColor" />
    }
    else
    {
        @Text

        @if (!HideIcon)
        {
            <FluentIcon Value="@_icon" Color="@IconColor" Slot="end" />
        }
    }
</FluentButton>

<FluentMenu Anchor="@MenuButtonId" aria-labelledby="button" @bind-Open="@_visible" VerticalThreshold="200">
    @foreach (var item in Items)
    {
        @if (item.IsDivider)
        {
            <FluentDivider />
        }
        else
        {
            var additionalMenuItemAttributes = new Dictionary<string, object>(item.AdditionalAttributes ?? ImmutableDictionary<string, object>.Empty)
            {
                { "title", item.Tooltip ?? item.Text ?? string.Empty }
            };

            <FluentMenuItem Id="@item.Id" Class="@item.Class" OnClick="() => HandleItemClicked(item)" Disabled="@item.IsDisabled" AdditionalAttributes="@additionalMenuItemAttributes">
                @item.Text
                @if (item.Icon != null)
                {
                    <span slot="start">
                        <FluentIcon Value="@item.Icon" Style="vertical-align: text-bottom;" Width="16px" />
                    </span>
                }
            </FluentMenuItem>
        }
    }
</FluentMenu>
